package cn.cdutetc.library.controller;

import cn.cdutetc.library.common.ApiResponse;
import cn.cdutetc.library.entity.pojo.BackupRecord;
import cn.cdutetc.library.entity.pojo.SystemLog;
import cn.cdutetc.library.entity.pojo.User;
import cn.cdutetc.library.mapper.SystemLogMapper;
import cn.cdutetc.library.service.BackupService;
import cn.cdutetc.library.service.SystemLogService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 备份管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/backup")
@CrossOrigin(originPatterns = "*")
public class BackupController {

    @Autowired
    private BackupService backupService;
    
    @Autowired
    private SystemLogService systemLogService;
    
    @Autowired
    private SystemLogMapper systemLogMapper;

    /**
     * 创建备份
     */
    @PostMapping("/create")
    public ApiResponse<BackupRecord> createBackup(@RequestBody Map<String, String> request) {
        try {
            String backupName = request.get("backupName");
            String description = request.get("description");
            
            if (backupName == null || backupName.trim().isEmpty()) {
                return ApiResponse.error("备份名称不能为空");
            }
            
            // 模拟当前用户（实际应用中从JWT或Session中获取）
            User currentUser = new User();
            currentUser.setUserId(null); // 暂时使用null避免外键约束问题
            currentUser.setRealName("系统管理员");
            
            BackupRecord backupRecord = backupService.createBackup(backupName, description, currentUser);
            return ApiResponse.success(backupRecord);
        } catch (Exception e) {
            log.error("创建备份失败", e);
            return ApiResponse.error("创建备份失败: " + e.getMessage());
        }
    }


    /**
     * 删除备份
     */
    @DeleteMapping("/delete/{backupId}")
    public ApiResponse<String> deleteBackup(@PathVariable Integer backupId) {
        try {
            // 模拟当前用户
            User currentUser = new User();
            currentUser.setUserId(null); // 暂时使用null避免外键约束问题
            currentUser.setRealName("系统管理员");
            
            boolean success = backupService.deleteBackup(backupId, currentUser);
            if (success) {
                return ApiResponse.success("删除备份成功");
            } else {
                return ApiResponse.error("删除备份失败");
            }
        } catch (Exception e) {
            log.error("删除备份失败", e);
            return ApiResponse.error("删除备份失败: " + e.getMessage());
        }
    }

    /**
     * 获取备份列表
     */
    @GetMapping("/list")
    public ApiResponse<Page<BackupRecord>> getBackupList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Page<BackupRecord> backupList = backupService.getBackupList(page, size);
            return ApiResponse.success(backupList);
        } catch (Exception e) {
            log.error("获取备份列表失败", e);
            return ApiResponse.error("获取备份列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取备份详情
     */
    @GetMapping("/detail/{backupId}")
    public ApiResponse<BackupRecord> getBackupDetail(@PathVariable Integer backupId) {
        try {
            BackupRecord backupRecord = backupService.getBackupById(backupId);
            if (backupRecord == null) {
                return ApiResponse.error("备份记录不存在");
            }
            return ApiResponse.success(backupRecord);
        } catch (Exception e) {
            log.error("获取备份详情失败", e);
            return ApiResponse.error("获取备份详情失败: " + e.getMessage());
        }
    }

    /**
     * 获取系统日志列表
     */
    @GetMapping("/logs")
    public ApiResponse<Page<SystemLog>> getSystemLogList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Page<SystemLog> logList = backupService.getSystemLogList(page, size);
            return ApiResponse.success(logList);
        } catch (Exception e) {
            log.error("获取系统日志失败", e);
            return ApiResponse.error("获取系统日志失败: " + e.getMessage());
        }
    }



    /**
     * 获取备份统计信息
     */
    @GetMapping("/statistics")
    public ApiResponse<Map<String, Object>> getBackupStatistics() {
        try {
            // 获取备份总数
            long totalBackups = backupService.getBackupList(1, 1).getTotal();
            
            // 获取成功备份数
            long successBackups = backupService.getBackupList(1, 1).getTotal();
            
            // 获取失败备份数
            long failedBackups = 0; // 可以根据状态筛选
            
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalBackups", totalBackups);
            statistics.put("successBackups", successBackups);
            statistics.put("failedBackups", failedBackups);
            
            return ApiResponse.success(statistics);
        } catch (Exception e) {
            log.error("获取备份统计信息失败", e);
            return ApiResponse.error("获取备份统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 打开备份文件夹
     */
    @PostMapping("/open-folder")
    public ApiResponse<String> openBackupFolder(@RequestBody Map<String, String> request) {
        try {
            String folderPath = request.get("path");
            if (folderPath == null || folderPath.trim().isEmpty()) {
                return ApiResponse.error("文件夹路径不能为空");
            }
            
            // 在Windows系统上使用explorer命令打开文件夹
            String os = System.getProperty("os.name").toLowerCase();
            if (os.contains("windows")) {
                ProcessBuilder processBuilder = new ProcessBuilder("explorer", folderPath);
                processBuilder.start();
                log.info("已打开备份文件夹: {}", folderPath);
                return ApiResponse.success("文件夹已打开");
            } else {
                // 其他操作系统
                return ApiResponse.error("当前操作系统不支持自动打开文件夹");
            }
        } catch (Exception e) {
            log.error("打开备份文件夹失败", e);
            return ApiResponse.error("打开备份文件夹失败: " + e.getMessage());
        }
    }

    /**
     * 导出系统日志
     */
    @GetMapping("/export-logs")
    public void exportLogs(
            @RequestParam(defaultValue = "csv") String format,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String logLevel,
            HttpServletResponse response) {
        try {
            // 设置响应头
            String fileName = "system_logs_" + java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            
            if ("csv".equals(format)) {
                response.setContentType("text/csv;charset=UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv");
                exportLogsToCsv(response, startDate, endDate, logLevel);
            } else if ("txt".equals(format)) {
                response.setContentType("text/plain;charset=UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".txt");
                exportLogsToTxt(response, startDate, endDate, logLevel);
            } else if ("json".equals(format)) {
                response.setContentType("application/json;charset=UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".json");
                exportLogsToJson(response, startDate, endDate, logLevel);
            } else {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().write("不支持的导出格式");
            }
        } catch (Exception e) {
            log.error("导出日志失败", e);
            try {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("导出日志失败: " + e.getMessage());
            } catch (Exception ex) {
                log.error("写入错误响应失败", ex);
            }
        }
    }

    /**
     * 导出日志为CSV格式
     */
    private void exportLogsToCsv(HttpServletResponse response, String startDate, String endDate, String logLevel) throws Exception {
        PrintWriter writer = response.getWriter();
        
        // 写入CSV头部
        writer.println("操作时间,用户,IP地址,操作类型,模块,级别,备注");
        
        // 获取日志数据
        Page<SystemLog> logPage = backupService.getSystemLogList(1, 10000); // 获取大量数据
        List<SystemLog> logs = logPage.getRecords();
        
        // 过滤数据
        if (startDate != null || endDate != null || logLevel != null) {
            logs = filterLogs(logs, startDate, endDate, logLevel);
        }
        
        // 写入数据
        for (SystemLog log : logs) {
            writer.println(String.format("%s,%s,%s,%s,%s,%s,%s",
                log.getOperationTime(),
                log.getUserName() != null ? log.getUserName() : "",
                log.getIpAddress() != null ? log.getIpAddress() : "",
                log.getOperation() != null ? log.getOperation() : "",
                log.getModule() != null ? log.getModule() : "",
                log.getLogLevel() != null ? log.getLogLevel() : "",
                log.getRemark() != null ? log.getRemark().replace(",", "，") : "" // 替换逗号避免CSV格式问题
            ));
        }
        
        writer.flush();
    }

    /**
     * 导出日志为TXT格式
     */
    private void exportLogsToTxt(HttpServletResponse response, String startDate, String endDate, String logLevel) throws Exception {
        PrintWriter writer = response.getWriter();
        
        // 获取日志数据
        Page<SystemLog> logPage = backupService.getSystemLogList(1, 10000);
        List<SystemLog> logs = logPage.getRecords();
        
        // 过滤数据
        if (startDate != null || endDate != null || logLevel != null) {
            logs = filterLogs(logs, startDate, endDate, logLevel);
        }
        
        // 写入数据
        writer.println("系统日志导出");
        writer.println("导出时间: " + java.time.LocalDateTime.now());
        writer.println("记录数量: " + logs.size());
        writer.println("=" + "=".repeat(80));
        writer.println();
        
        for (SystemLog log : logs) {
            writer.println("时间: " + log.getOperationTime());
            writer.println("用户: " + (log.getUserName() != null ? log.getUserName() : "系统"));
            writer.println("IP: " + (log.getIpAddress() != null ? log.getIpAddress() : ""));
            writer.println("操作: " + (log.getOperation() != null ? log.getOperation() : ""));
            writer.println("模块: " + (log.getModule() != null ? log.getModule() : ""));
            writer.println("级别: " + (log.getLogLevel() != null ? log.getLogLevel() : ""));
            writer.println("备注: " + (log.getRemark() != null ? log.getRemark() : ""));
            writer.println("-".repeat(80));
            writer.println();
        }
        
        writer.flush();
    }

    /**
     * 导出日志为JSON格式
     */
    private void exportLogsToJson(HttpServletResponse response, String startDate, String endDate, String logLevel) throws Exception {
        PrintWriter writer = response.getWriter();
        
        // 获取日志数据
        Page<SystemLog> logPage = backupService.getSystemLogList(1, 10000);
        List<SystemLog> logs = logPage.getRecords();
        
        // 过滤数据
        if (startDate != null || endDate != null || logLevel != null) {
            logs = filterLogs(logs, startDate, endDate, logLevel);
        }
        
        // 构建JSON
        writer.println("{");
        writer.println("  \"exportTime\": \"" + java.time.LocalDateTime.now() + "\",");
        writer.println("  \"totalCount\": " + logs.size() + ",");
        writer.println("  \"logs\": [");
        
        for (int i = 0; i < logs.size(); i++) {
            SystemLog log = logs.get(i);
            writer.println("    {");
            writer.println("      \"operationTime\": \"" + log.getOperationTime() + "\",");
            writer.println("      \"userName\": \"" + (log.getUserName() != null ? log.getUserName() : "") + "\",");
            writer.println("      \"ipAddress\": \"" + (log.getIpAddress() != null ? log.getIpAddress() : "") + "\",");
            writer.println("      \"operation\": \"" + (log.getOperation() != null ? log.getOperation() : "") + "\",");
            writer.println("      \"module\": \"" + (log.getModule() != null ? log.getModule() : "") + "\",");
            writer.println("      \"logLevel\": \"" + (log.getLogLevel() != null ? log.getLogLevel() : "") + "\",");
            writer.println("      \"remark\": \"" + (log.getRemark() != null ? log.getRemark().replace("\"", "\\\"") : "") + "\"");
            writer.print("    }");
            if (i < logs.size() - 1) {
                writer.println(",");
            } else {
                writer.println();
            }
        }
        
        writer.println("  ]");
        writer.println("}");
        
        writer.flush();
    }

    /**
     * 过滤日志数据
     */
    private List<SystemLog> filterLogs(List<SystemLog> logs, String startDate, String endDate, String logLevel) {
        return logs.stream()
            .filter(log -> {
                if (startDate != null && !startDate.isEmpty()) {
                    if (log.getOperationTime().isBefore(java.time.LocalDateTime.parse(startDate + "T00:00:00"))) {
                        return false;
                    }
                }
                if (endDate != null && !endDate.isEmpty()) {
                    if (log.getOperationTime().isAfter(java.time.LocalDateTime.parse(endDate + "T23:59:59"))) {
                        return false;
                    }
                }
                if (logLevel != null && !logLevel.isEmpty()) {
                    if (!logLevel.equals(log.getLogLevel())) {
                        return false;
                    }
                }
                return true;
            })
            .collect(java.util.stream.Collectors.toList());
    }

    /**
     * 导入日志文件
     */
    @PostMapping("/import-logs")
    public ApiResponse<Map<String, Object>> importLogs(
            @RequestParam("file") MultipartFile file,
            @RequestParam(defaultValue = "auto") String format) {
        try {
            if (file.isEmpty()) {
                return ApiResponse.error("请选择要导入的文件");
            }

            String fileName = file.getOriginalFilename();
            if (fileName == null || (!fileName.endsWith(".csv") && !fileName.endsWith(".txt") && !fileName.endsWith(".json"))) {
                return ApiResponse.error("不支持的文件格式，请选择CSV、TXT或JSON文件");
            }

            // 自动检测文件格式
            String detectedFormat = format;
            if ("auto".equals(format)) {
                if (fileName.endsWith(".csv")) {
                    detectedFormat = "csv";
                } else if (fileName.endsWith(".txt")) {
                    detectedFormat = "txt";
                } else if (fileName.endsWith(".json")) {
                    detectedFormat = "json";
                }
            }

            Map<String, Object> result = new HashMap<>();
            int successCount = 0;
            int errorCount = 0;
            List<String> errors = new ArrayList<>();

            try {
                switch (detectedFormat) {
                    case "csv":
                        result = importLogsFromCsv(file);
                        break;
                    case "txt":
                        result = importLogsFromTxt(file);
                        break;
                    case "json":
                        result = importLogsFromJson(file);
                        break;
                    default:
                        return ApiResponse.error("不支持的文件格式: " + detectedFormat);
                }

                successCount = (Integer) result.get("successCount");
                errorCount = (Integer) result.get("errorCount");
                @SuppressWarnings("unchecked")
                List<String> errorList = (List<String>) result.get("errors");
                errors = errorList;

            } catch (Exception e) {
                log.error("导入日志文件失败", e);
                return ApiResponse.error("导入日志文件失败: " + e.getMessage());
            }

            Map<String, Object> response = new HashMap<>();
            response.put("fileName", fileName);
            response.put("format", detectedFormat);
            response.put("successCount", successCount);
            response.put("errorCount", errorCount);
            response.put("totalCount", successCount + errorCount);
            response.put("errors", errors);

            if (errorCount > 0) {
                response.put("message", String.format("导入完成，成功 %d 条，失败 %d 条", successCount, errorCount));
            } else {
                response.put("message", String.format("导入成功，共导入 %d 条日志记录", successCount));
            }

            return ApiResponse.success(response);

        } catch (Exception e) {
            log.error("导入日志失败", e);
            return ApiResponse.error("导入日志失败: " + e.getMessage());
        }
    }

    /**
     * 从CSV文件导入日志
     */
    private Map<String, Object> importLogsFromCsv(MultipartFile file) throws Exception {
        List<String> lines = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream(), "UTF-8"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        }

        int successCount = 0;
        int errorCount = 0;
        List<String> errors = new ArrayList<>();

        // 跳过标题行
        for (int i = 1; i < lines.size(); i++) {
            try {
                String[] fields = lines.get(i).split(",");
                if (fields.length >= 7) {
                    SystemLog log = new SystemLog();
                    log.setLogCode("LOG" + System.currentTimeMillis() + "_" + i);
                    log.setUserName(fields[1].trim());
                    log.setIpAddress(fields[2].trim());
                    log.setOperation(fields[3].trim());
                    log.setModule(fields[4].trim());
                    log.setLogLevel(fields[5].trim());
                    log.setRemark(fields[6].trim());
                    log.setOperationTime(java.time.LocalDateTime.parse(fields[0].trim()));

                    backupService.saveSystemLog(log);
                    successCount++;
                } else {
                    errorCount++;
                    errors.add("第" + (i + 1) + "行字段不足");
                }
            } catch (Exception e) {
                errorCount++;
                errors.add("第" + (i + 1) + "行解析失败: " + e.getMessage());
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("successCount", successCount);
        result.put("errorCount", errorCount);
        result.put("errors", errors);
        return result;
    }

    /**
     * 从TXT文件导入日志
     */
    private Map<String, Object> importLogsFromTxt(MultipartFile file) throws Exception {
        String content = new String(file.getBytes(), "UTF-8");
        String[] sections = content.split("=" + "=".repeat(80));

        int successCount = 0;
        int errorCount = 0;
        List<String> errors = new ArrayList<>();

        for (int i = 1; i < sections.length; i++) { // 跳过第一个空section
            try {
                String section = sections[i].trim();
                if (section.isEmpty()) continue;

                SystemLog log = new SystemLog();
                log.setLogCode("LOG" + System.currentTimeMillis() + "_" + i);

                String[] lines = section.split("\n");
                for (String line : lines) {
                    if (line.startsWith("时间: ")) {
                        log.setOperationTime(java.time.LocalDateTime.parse(line.substring(3).trim()));
                    } else if (line.startsWith("用户: ")) {
                        log.setUserName(line.substring(3).trim());
                    } else if (line.startsWith("IP: ")) {
                        log.setIpAddress(line.substring(3).trim());
                    } else if (line.startsWith("操作: ")) {
                        log.setOperation(line.substring(3).trim());
                    } else if (line.startsWith("模块: ")) {
                        log.setModule(line.substring(3).trim());
                    } else if (line.startsWith("级别: ")) {
                        log.setLogLevel(line.substring(3).trim());
                    } else if (line.startsWith("备注: ")) {
                        log.setRemark(line.substring(3).trim());
                    }
                }

                backupService.saveSystemLog(log);
                successCount++;
            } catch (Exception e) {
                errorCount++;
                errors.add("第" + i + "个日志记录解析失败: " + e.getMessage());
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("successCount", successCount);
        result.put("errorCount", errorCount);
        result.put("errors", errors);
        return result;
    }

    /**
     * 删除日志记录
     */
    @DeleteMapping("/delete-log/{logId}")
    public ApiResponse<String> deleteLog(@PathVariable Long logId) {
        try {
            // 检查日志是否存在
            SystemLog systemLog = systemLogMapper.selectById(logId);
            if (systemLog == null) {
                return ApiResponse.error("日志记录不存在");
            }

            // 删除日志
            int result = systemLogMapper.deleteById(logId);
            if (result > 0) {
                log.info("删除日志记录成功: {}", logId);
                return ApiResponse.success("删除成功");
            } else {
                return ApiResponse.error("删除失败");
            }
        } catch (Exception e) {
            log.error("删除日志记录失败", e);
            return ApiResponse.error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除日志记录
     */
    @PostMapping("/batch-delete-logs")
    public ApiResponse<Map<String, Object>> batchDeleteLogs(@RequestBody Map<String, Object> request) {
        try {
            @SuppressWarnings("unchecked")
            List<Long> logIds = (List<Long>) request.get("logIds");
            
            if (logIds == null || logIds.isEmpty()) {
                return ApiResponse.error("请选择要删除的日志记录");
            }

            int successCount = 0;
            int errorCount = 0;
            List<String> errors = new ArrayList<>();

            for (Long logId : logIds) {
                try {
                    int result = systemLogMapper.deleteById(logId);
                    if (result > 0) {
                        successCount++;
                    } else {
                        errorCount++;
                        errors.add("日志ID " + logId + " 删除失败");
                    }
                } catch (Exception e) {
                    errorCount++;
                    errors.add("日志ID " + logId + " 删除失败: " + e.getMessage());
                }
            }

            Map<String, Object> response = new HashMap<>();
            response.put("successCount", successCount);
            response.put("errorCount", errorCount);
            response.put("totalCount", logIds.size());
            response.put("errors", errors);

            if (errorCount > 0) {
                response.put("message", String.format("批量删除完成，成功 %d 条，失败 %d 条", successCount, errorCount));
            } else {
                response.put("message", String.format("批量删除成功，共删除 %d 条日志记录", successCount));
            }

            return ApiResponse.success(response);

        } catch (Exception e) {
            log.error("批量删除日志记录失败", e);
            return ApiResponse.error("批量删除失败: " + e.getMessage());
        }
    }

    /**
     * 清空所有日志记录
     */
    @DeleteMapping("/clear-all-logs")
    public ApiResponse<String> clearAllLogs() {
        try {
            // 获取删除前的记录数
            Long totalCount = systemLogMapper.selectCount(null);
            
            // 清空所有日志
            systemLogMapper.delete(null);
            
            log.info("清空所有日志记录成功，共删除 {} 条记录", totalCount);
            return ApiResponse.success(String.format("清空成功，共删除 %d 条日志记录", totalCount));
        } catch (Exception e) {
            log.error("清空所有日志记录失败", e);
            return ApiResponse.error("清空失败: " + e.getMessage());
        }
    }

    /**
     * 按条件删除日志记录
     */
    @PostMapping("/delete-logs-by-condition")
    public ApiResponse<Map<String, Object>> deleteLogsByCondition(@RequestBody Map<String, Object> request) {
        try {
            String startDate = (String) request.get("startDate");
            String endDate = (String) request.get("endDate");
            String logLevel = (String) request.get("logLevel");
            String module = (String) request.get("module");

            // 构建查询条件
            QueryWrapper<SystemLog> queryWrapper = new QueryWrapper<>();
            
            if (startDate != null && !startDate.isEmpty()) {
                queryWrapper.ge("operation_time", startDate + " 00:00:00");
            }
            if (endDate != null && !endDate.isEmpty()) {
                queryWrapper.le("operation_time", endDate + " 23:59:59");
            }
            if (logLevel != null && !logLevel.isEmpty()) {
                queryWrapper.eq("log_level", logLevel);
            }
            if (module != null && !module.isEmpty()) {
                queryWrapper.eq("module", module);
            }

            // 获取符合条件的记录数
            Long totalCount = systemLogMapper.selectCount(queryWrapper);
            
            if (totalCount == 0) {
                Map<String, Object> response = new HashMap<>();
                response.put("totalCount", 0);
                response.put("deletedCount", 0);
                response.put("message", "没有符合条件的日志记录");
                return ApiResponse.success(response);
            }

            // 删除符合条件的记录
            int deletedCount = systemLogMapper.delete(queryWrapper);
            
            Map<String, Object> response = new HashMap<>();
            response.put("totalCount", totalCount);
            response.put("deletedCount", deletedCount);
            response.put("message", String.format("按条件删除成功，共删除 %d 条日志记录", deletedCount));

            return ApiResponse.success(response);

        } catch (Exception e) {
            log.error("按条件删除日志记录失败", e);
            return ApiResponse.error("按条件删除失败: " + e.getMessage());
        }
    }

    /**
     * 从JSON文件导入日志
     */
    private Map<String, Object> importLogsFromJson(MultipartFile file) throws Exception {
        String content = new String(file.getBytes(), "UTF-8");
        
        // 简单的JSON解析（实际项目中建议使用Jackson等库）
        int successCount = 0;
        int errorCount = 0;
        List<String> errors = new ArrayList<>();

        try {
            // 这里需要实现JSON解析逻辑
            // 由于没有引入JSON库，这里提供一个简化的实现
            if (content.contains("\"logs\"")) {
                // 找到logs数组部分
                int logsStart = content.indexOf("\"logs\": [") + 9;
                int logsEnd = content.lastIndexOf("]");
                String logsContent = content.substring(logsStart, logsEnd);
                
                // 简单的JSON对象解析
                String[] logObjects = logsContent.split("\\},\\s*\\{");
                for (int i = 0; i < logObjects.length; i++) {
                    try {
                        String logStr = logObjects[i].trim();
                        if (logStr.startsWith("{")) {
                            logStr = logStr.substring(1);
                        }
                        if (logStr.endsWith("}")) {
                            logStr = logStr.substring(0, logStr.length() - 1);
                        }

                        SystemLog log = new SystemLog();
                        log.setLogCode("LOG" + System.currentTimeMillis() + "_" + i);

                        // 解析各个字段
                        String[] fields = logStr.split(",");
                        for (String field : fields) {
                            String[] kv = field.split(":");
                            if (kv.length == 2) {
                                String key = kv[0].trim().replace("\"", "");
                                String value = kv[1].trim().replace("\"", "");
                                
                                switch (key) {
                                    case "operationTime":
                                        log.setOperationTime(java.time.LocalDateTime.parse(value));
                                        break;
                                    case "userName":
                                        log.setUserName(value);
                                        break;
                                    case "ipAddress":
                                        log.setIpAddress(value);
                                        break;
                                    case "operation":
                                        log.setOperation(value);
                                        break;
                                    case "module":
                                        log.setModule(value);
                                        break;
                                    case "logLevel":
                                        log.setLogLevel(value);
                                        break;
                                    case "remark":
                                        log.setRemark(value);
                                        break;
                                }
                            }
                        }

                        backupService.saveSystemLog(log);
                        successCount++;
                    } catch (Exception e) {
                        errorCount++;
                        errors.add("第" + (i + 1) + "个JSON对象解析失败: " + e.getMessage());
                    }
                }
            }
        } catch (Exception e) {
            errorCount++;
            errors.add("JSON文件格式错误: " + e.getMessage());
        }

        Map<String, Object> result = new HashMap<>();
        result.put("successCount", successCount);
        result.put("errorCount", errorCount);
        result.put("errors", errors);
        return result;
    }
}
